package com.googlecode.placesapiclient.client.connection;

import com.googlecode.placesapiclient.client.connection.proxy.ProxyConfiguration;
import org.apache.commons.codec.binary.Base64;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

/**
 */
public class ConnectionFactory {


    public static URLConnection getURLConnection(URL pURL, ProxyConfiguration proxyConfiguration) throws IOException {

        if(proxyConfiguration == null) {
            return pURL.openConnection();
        } else {
            return getProxyBasedUrlConnection(pURL, proxyConfiguration);
        }

    }

    private static URLConnection getProxyBasedUrlConnection(URL pURL, ProxyConfiguration proxyConfiguration) throws IOException {

        System.setProperty("http.proxyHost", proxyConfiguration.getProxyHost());
        System.setProperty("http.proxyPort", proxyConfiguration.getProxyPort());
        System.setProperty("https.proxyHost", proxyConfiguration.getProxyHost());
        System.setProperty("https.proxyPort", proxyConfiguration.getProxyPort());
        URLConnection urlConnection = pURL.openConnection();

        if(proxyConfiguration.getProxyCredentials()!=null) {
            String auth = new String(Base64.encodeBase64((proxyConfiguration.getProxyCredentials().getProxyUsername() + ":" + proxyConfiguration.getProxyCredentials().getProxyPassword()).getBytes()));
            auth = "Basic " + auth;
            urlConnection.setRequestProperty("Proxy-Authorization",auth);
        }

        urlConnection.setRequestProperty("Proxy-Connection","Keep-Alive");
        return urlConnection;
    }

    private static URLConnection getURLConnection(URL pURL) throws IOException {
        return pURL.openConnection();
    }
}
